package cn.sofwin.blog.service.impl;

import cn.sofwin.blog.dao.ArticleDao;
import cn.sofwin.blog.entity.Article;
import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.service.ArticleService;
import cn.sofwin.blog.utils.Dbutils;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

/**
 * 服务层
 * @author zx
 * @since 1.0
 *
 */
public class ArticleServiceImpl implements ArticleService {

    /** 私有的实例对象，用户实现单例模式 */
    private static ArticleServiceImpl articleService = new ArticleServiceImpl();

    /**
     * 将构造方法设为私有，用于实现单例模式
     */
    private ArticleServiceImpl(){
        super();
    }

    /**
     * 对外提供的静态方法，用于获取服务实例
     * @return
     */
    public static ArticleService getInstance(){
        return articleService;
    }

    @Override
   public SqlSession getSession() {
        return Dbutils.openSession();
    }

    @Override
    public List<Article> all() {
        return this.getSession().getMapper(ArticleDao.class).all();

    }

    @Override
    public Article get(Integer id) {
        return this.getSession().getMapper(ArticleDao.class).selectOne(id);
    }

    @Override
    public void addReadTotal(String id) {
          this.getSession().getMapper(ArticleDao.class).addReadTotal(id);
    }

    @Override
    public void publish(User user, String title, String summary, String content) {
        Article article = new Article();
        article.setUser(user);
        article.setTitle(title);
        article.setSummary(summary);
        article.setContent(content);
        article.setAddTime(new Date());

        articleService.getSession().getMapper(ArticleDao.class).insert(article);
    }

    @Override
    public void edit(User user, String id, String title, String summary, String content) {

        Integer aid = Integer.valueOf(id);
        Article article = articleService.get(aid);

        // 无效ID，终止更新操作
        if(article == null){
            return;
        }
        // 判断文章是否为当前用户发表，如果不是，则终止更新操作
        if(!user.getId().equals( article.getUser().getId() )){
            return;
        }
        // 所有校验通过，开始更新，不允许修改文章标题
        article.setSummary(summary);
        article.setContent(content);
        articleService.getSession().getMapper(ArticleDao.class).update(article);

    }

    @Override
    public void remove(Integer aid) {
        articleService.getSession().getMapper(ArticleDao.class).deleteById(aid);
    }

}